var dataList;
var outer = $("#js_data_list_outer");
var FileCheckHandler;	//操作铵钮状态设置
var FileRightHandler;	//打开右键菜单
var _pageShowFreeTimer;
var _loadDetailTimer;
var _hideDescList = [33, 7];    //隐藏描述ID
var _freeSideData;  
var _loadingfreeData = false;
var _showMenuTimer;
var page_cache = {}	//页面缓存
//绑定
var lineHeight;	//行高 
var lineWidth;	//行宽

var innerBox = $("#js_data_list");

var PageDocumentSelectState = false;
if(typeof window["NotPutAPI"] == "undefined"){
    var NotPutAPI = false;
}

function getAddress(gps){
    
    var address = ""; //地理位置
    var arr = gps.split(",");
    var locat = new google.maps.LatLng(arr[0], arr[1]); 
    var geocoder = new google.maps.Geocoder(); 
    //var address;
    geocoder.geocode({'latLng': locat}, function(results, status) { 
        //异步解析gps地址 
        if (status == google.maps.GeocoderStatus.OK) { 
            if (results[2]) { 
                address = results[2].formatted_address;
                address = address.replace("中国", "");
                $("#filelocation").attr("title",address);
                if (address.length > 9) {
                    address = address.substring(0,9) + "...";
                };
               
                $("#filelocation").html(address);
                
            }
        }
    });
   return address;
}

//停止冒泡
var page_stopPropagation = function(e){
	if($.browser.msie){
		event.cancelBubble=true;
	}else{
		e.stopPropagation();
		e.preventDefault();
	}	//停止冒泡
}

//检查是否有详细信息
var CheckHasDesc = function(){
    var result = true;
    for(var i = 0, len = _hideDescList.length; i < len; i++){
        if(dataSource.aid == _hideDescList[i]){
            result = false;
        }
    }
    return result;
}

//显示当前目录详细信息
var SetFreeDetail = function(){
    if(_freeSideData){
        var d = _freeSideData;
        var box = $("#js_right_side"); 
        if(box.attr("is_free") == "1"){
            if(d.is_share == "1"){
                box.find(".file-thumb").html('<b class="shared"></b>');
            }
            
            var ul = $("<ul></ul>");
            if(d.is_share == "1"){
//                ul.append('<li><i class="fl">提取码：<a title="进入分享页" href="'+downURI+'/folder/'+d["pick_code"]+'" target="_blank">' + d["pick_code"] + '</a></i> <a href="javascript:;" class="fr" pick_code="' + d["pick_code"] + '" title="复制分享地址">复制地址</a>');
                
            }
            ul.append('<li><i class="fl">创建时间：</i><span class="fr" detail="ptime">' + d.ptime + '</span></li>');
            if(dataSource.aid == 3 || dataSource.aid == 4){
//                ul.append('<li><i class="fl">编辑封面：</i>'+
//                                '<span class="fr">'+
//                                    '<a href="javascript:;" class="icon ico-cover" rel="edit_cover" title="编辑封面">编辑</a>'+
//                                '</span></li>');
            }
            
            if(d["category_file_count"]){
                ul.append('<li><i class="fl">当前目录包含:</i><span class="fr">' + d["category_file_count"] + '个文件</span></li>');
            }
            
            box.find(".file-info").append(ul);
            box.find('[pick_code]').bind("click", function(e){
                Util.Copy(downURI + "/folder/" + $(this).attr("pick_code"));
            })
            box.find("[rel='edit_cover']").bind("click", {cid: dataSource.cid}, function(e){
                // 编辑封面
                parent.window.Main.Core.FileSelectDG.EditCover(dataSource.aid, e.data.cid);
            })
        }
    }
    GetFreeAdImage();
}
var ShowFreeMsg = function(){
	if(window.NoRightSide){return;}
    HideFreeAdImage();
	//没有选择记录
	var box = $("#js_right_side");
    box.attr("is_free", "1");
    if(dataSource){
        var cid = dataSource.cid;
        if(cid == 0){
            cid = dataSource.aid + "_0";
        }
        if(cid == -1){
            cid = dataSource.aid + "_0";
        }
        
        var node = LIST_CONFIG.active;
        var folder = cid.toString().indexOf("_0") == -1 ? "tb-folder" : false;
        switch(dataSource.aid){
            case 1:case 2:case 3:case 4:case 5:case 9:
                if(!node){
                    window.location.href = "?ct=file&ac=userfile&aid=-1&cid=-1&_t=" + new Date().getTime();
                    return;
                }
                if(dataSource.cid != 0 && !_freeSideData){
                    if(!_loadingfreeData){
                        window.setTimeout(function(){
                            _loadingfreeData = true;
                            parent.window.Main.Core.FileAjax.GetDirDetail(dataSource.aid, dataSource.cid, function(data){
                                _loadingfreeData = false;
                                _freeSideData = data;
                                SetFreeDetail();
                            })
                        }, 10);
                    }
                }
                break;
        }
        switch(dataSource.aid){
            case 0:
                var html = '<div class="file-info"></div>' +
                    '<div class="sub-tips">' +
                            '<h3><i class="icon ico-tips"></i>临时空间变动说明</h3>' +
                            '<ul>' +
                                '<li>• 原临时空间已转换成永久空间</li>' +
                                '<li>• 总空间 = 原临时空间 + 原永久空间</li>' +
                                '<li>• 本目录不能上传，可转移、删除 </li>' +
                            '</ul>' +
                        '</div>';
                box.html(html);
                break;
            case 1:

                var html = '<div class="file-info">'+
                            '<div class="file-thumb '+ (folder?folder:'folder-file') + '"></div>'+

                            '<div class="thumb-name">'+node.name+'</div>' +
                            '</div>' +
                    '<div class="sub-tips">' +
                            '<h3><i class="icon ico-tips"></i>小贴士</h3>' +
                            '<ul>' +
                                '<li>• 可以存放任何格式的文件 </li>' +
                                '<li>• 分类整理养成良好习惯 </li>' +  
                            '</ul>' +
                        '</div>';
                box.html(html);
                break;
            case 2:
                var html = '<div class="file-info">'+
                            '<div class="file-thumb '+ (folder?folder:'folder-document') + '"></div>'+
                            '<div class="thumb-name">'+node.name+'</div>' +
                            '</div>' +
                    '<div class="sub-tips">' +
                            '<h3><i class="icon ico-tips"></i>小贴士</h3>' +
                            '<ul>' +
                                '<li>• 本类存放各类办公文档 </li>' + 
                            '</ul>' +
                        '</div>';
                box.html(html);
                break;
            case 3:

                var html = '<div class="file-info">'+
                            '<div class="file-thumb '+ (folder?folder:'folder-photo') + '"></div>'+

                            '<div class="thumb-name">'+node.name+'</div>'+
                            '</div>';

                html += '<div class="sub-tips">' +
                            '<h3><i class="icon ico-tips"></i>小贴士</h3>' +
                            '<ul>' +
                                '<li>• 照片图库管理专区 </li>' +
                                '<li>• 超炫在线预览效果 </li>' + 
                                '<li>• 精彩瞬间永久回忆</li>' +
                            '</ul>' +
                        '</div>';
                box.html(html);
                break;
            case 4:

                var html = '<div class="file-info">'+
                            '<div class="file-thumb '+ (folder?folder:'folder-music') + '"></div>'+

                            '<div class="thumb-name">'+node.name+'</div>' +
                            '</div>' +
                            '<div class="sub-tips">' +
                                '<h3><i class="icon ico-tips"></i>小贴士</h3>' +
                                '<ul>' +
                                    '<li>• 本类存储各种音频文件 </li>' +
                                    '<li>• 无需下载即可在线播放 </li>' +
                                    '<li>• 列表播放音乐随心享用 </li>' +
                                '</ul>' +
                            '</div>';
                box.html(html);
                break;
            case 5:

                var persent;
                if(!folder){
                    persent = dataSource.attachment.size_used_percent.toFixed(2) + "%";
                }


                var html = '<div class="file-info">'+
                            '<div class="file-thumb '+ (folder?folder:'folder-accessory') + '"></div>'+

                            '<div class="thumb-name">'+node.name+'</div>' +
                            (folder? "" : '<ul>' + 
                                '<li>' +
                                    '<div class="space-status" title="总空间：'+Util.File.ShowSize(dataSource.attachment.size_total)+'，已使用：'+Util.File.ShowSize(dataSource.attachment.size_used)+'，使用率：'+persent+'"><i style="width:'+persent+'%;"></i></div>' +
                                '</li>' +
                                '<li><i class="fl">总空间：'+Util.File.ShowSize(dataSource.attachment.size_total)+'</i></li>' + 
                                '<li><i class="fl">已使用：'+Util.File.ShowSize(dataSource.attachment.size_used)+'</i></li>' + 
                                '<li><i class="fl">单文件上限：'+Util.File.ShowSize(dataSource.attachment.upload_size_limit)+'</i></li>' +
                            '</ul>') +
                            '</div>' +
                    '<div class="sub-tips">' +
                            '<h3><i class="icon ico-tips"></i>小贴士</h3>' +
                            '<ul>' +
                                '<li>• 存放通过附件通产生的附件</li>' +
                                '<li>• 该目录下的文件只允许删除操作</li>' +
                                '<li>• 更多操作请参考附件通官方网站</li>' +
                                '<li><a href="" target="_blank">aa</a></li>' +
                            '</ul>' +
                        '</div>';
                box.html(html);
                break;
           case 9:

                var html = '<div class="file-info">'+
                            '<div class="file-thumb '+ (folder?folder:'folder-video') + '"></div>'+
                            '<div class="thumb-name">'+node.name+'</div>' +
                            '</div>' +
                            '<div class="sub-tips">' +
                                '<h3><i class="icon ico-tips"></i>小贴士</h3>' +
                                '<ul>' +
                                    '<li>• 本类存储各种视频文件 </li>' +
                                '</ul>' +
                            '</div>';
                box.html(html);
                break;

          case 30: case 31: case 32: case 33: case 34:
                if(window["SideFreeTips"]){
                    box.html(window["SideFreeTips"]);
                }
                break;
          case 35:

              var html = '<div class="file-info">'+
                          '<div class="file-thumb folder-location"></div>'+
                          '<div class="thumb-name">'+node.name+'</div>' +
                          '</div>' +
                          '<div class="sub-tips">' +
                              '<h3><i class="icon ico-tips"></i>小贴士</h3>' +
                              '<ul>' +
                                  '<li>• 本类存储相同地理位置文件 </li>' +
                                  '<li>• 文件可能分布在不同目录下</li>' +
                                  '<li>• 方便您多方位查看相册</li>' +
                              '</ul>' +
                          '</div>';
              box.html(html);
              break;
        }
        SetFreeDetail();
    }
    
}

var _TjjSideAdBox, _TjjSideAdTimer;
var GetFreeAdImage = function(){
    if(_TjjSideAdTimer) window.clearTimeout(_TjjSideAdTimer);
    
    if(!_TjjSideAdBox){
        _TjjSideAdBox = $('<div style="position: absolute;right:7px;top:-99999px;"><iframe id="frame_tjj_29" style="height:140px;width:200px;" src="/statics/web/delivery/d_29.html" scrolling="no" frameborder="0"></iframe></div>');
        //$(document.body).append(_TjjSideAdBox);
    }
    
    _TjjSideAdTimer = window.setTimeout(function(){
        try{
            var box = $("#js_right_side");
            var childs = box.children();
            if(childs.length){
                
                var t = box.offset().top + box.height() + 10;
                if($(document).height() <= t + 140 + 57){
                    _TjjSideAdBox.css({top: "-99999px"});
                }
                else{
                    _TjjSideAdBox.css({top: t + "px"});
                }
            }
        }catch(e){}
    }, 50);
}

var HideFreeAdImage = function(){
    if(_TjjSideAdTimer) window.clearTimeout(_TjjSideAdTimer);
    if(_TjjSideAdBox){
        _TjjSideAdBox.css({top: "-99999px"});
    }
}

//显示右边信息栏
var ShowRightSide = function(arr){
    HideFreeAdImage();
    TopMenu.CheckMenu(arr);
	if(window.NoRightSide){return;}

	var box = $("#js_right_side");
	box.html("");
    box.removeAttr("is_free");
    if(_pageShowFreeTimer){
        window.clearTimeout(_pageShowFreeTimer);
    }
    var is_frumn = false;

    if(dataSource.aid == 5){
        is_frumn = true;
    }
	if(arr && arr.length){
        if(dataSource.aid == 7){
            ShowFreeMsg();
            return;
        }
		var html = [];
        if(_loadDetailTimer){
            window.clearTimeout(_loadDetailTimer);
        }
        
		if(arr.length == 1){
            
			var item = arr[0];
			switch(item.attr("file_type")){
				case "1":

					//选择了一个文件
					html.push('<div class="file-info">');

					if(item.attr('img_url')){
						html.push('<div class="thumb-wrap"><img src="'+item.attr('img_url')+'"><i></i></div>');

					}
					else{
						html.push('<div class="file-thumb tb-'+item.attr("ico")+'">'+ ((item.attr("is_share") == "1")? '<b class="shared"></b>': '') + '</div>');
					}

					var file_name = item.find('[field="file_name"]').attr("title");
					html.push('<div class="thumb-name" title="'+file_name+'">'+Util.Text.Cut(file_name,20) +'</div>');
                    switch(dataSource.aid){
                        case 1:
                        case 9:
                            html.push('<div class="btn-container"><span class="btn-wrap">'+
//                                        '<a href="'+downURI + "/file/" + item.attr("pick_code")+'" target="_blank" class="btn">打开</a>'+
                                        '<a href="javascript:;" class="btn" menu="download">下载</a>'+
//                                        (item.attr("is_share") == "1"? '<a href="javascript:;" class="btn" menu="renew">续期</a>' :'<a href="javascript:;" class="btn" menu="shareto">分享</a>') +
                                      '</span></div>');
                            break;
                            //send
                        case 2:
                            html.push('<div class="btn-container"><span class="btn-wrap">'+
//                                        '<a href="javascript:;" class="btn" menu="view_doc">预览</a>'+
                                        '<a href="javascript:;" class="btn" menu="download">下载</a>'+
//                                        (item.attr("is_share") == "1"? '<a href="javascript:;" class="btn" menu="renew">续期</a>' :'<a href="javascript:;" class="btn" menu="shareto">分享</a>')+
                                      '</span></div>');
                            break;
                        case 3:
                            html.push('<div class="btn-container"><span class="btn-wrap">'+
                                        '<a href="javascript:;" class="btn" menu="view_photo">预览</a>'+
                                        '<a href="javascript:;" class="btn" menu="download">下载</a>'+
//                                        '<a href="javascript:;" class="btn" menu="shareto">分享</a>'+
                                      '</span></div>');
                            break;
                        case 4:
                            html.push('<div class="btn-container"><span class="btn-wrap">'+
                                        '<a href="javascript:;" class="btn" menu="view_music">试听</a>'+
                                        '<a href="javascript:;" class="btn" menu="download">下载</a>'+
//                                        '<a href="javascript:;" class="btn" menu="shareto">分享</a>'+
                                      '</span></div>');
                            break;
                        
                        case 30: case 31: case 32: case 34: case -3:

                            var acAid = item.attr("area_id");
                            switch(Number(acAid)){
                                case 1:
                                case 9:
                                    var issend = (item.attr("is_share") == "1");
                                    if(dataSource.aid == 34){issend = true;}
                                    html.push('<div class="btn-container"><span class="btn-wrap">'+
//                                                '<a href="'+downURI + "/file/" + item.attr("pick_code")+'" target="_blank" class="btn">打开</a>'+
                                                '<a href="javascript:;" class="btn" menu="download">下载</a>'+
//                                                '<a href="javascript:;" class="btn" menu="shareto">分享</a>' +
                                              '</span></div>');
                                    break;
                                    //send
                                case 2:
                                    if(dataSource.aid == 34){issend = true;}
                                    html.push('<div class="btn-container"><span class="btn-wrap">'+
//                                                '<a href="javascript:;" class="btn" menu="view_doc">预览</a>'+
                                                '<a href="javascript:;" class="btn" menu="download">下载</a>'+
//                                                '<a href="javascript:;" class="btn" menu="shareto">分享</a>'+
                                              '</span></div>');
                                    break;
                                case 3:
                                    html.push('<div class="btn-container"><span class="btn-wrap">'+
                                                '<a href="javascript:;" class="btn" menu="view_photo">预览</a>'+
                                                '<a href="javascript:;" class="btn" menu="download">下载</a>'+
//                                                '<a href="javascript:;" class="btn" menu="shareto">分享</a>'+
                                              '</span></div>');
                                    break;
                                case 4:
                                    html.push('<div class="btn-container"><span class="btn-wrap">'+
                                                '<a href="javascript:;" class="btn" menu="view_music">试听</a>'+
                                                '<a href="javascript:;" class="btn" menu="download">下载</a>'+
//                                                '<a href="javascript:;" class="btn" menu="shareto">分享</a>'+
                                              '</span></div>');
                                    break;
                            }

                            break;
                    }


					html.push('<ul detail="ext_feild">');
                    
                    if(item.attr("file_status") == "2"){
                        html.push('<li><i class="fl">文件状态：</i><span class="fr">转移中</span></li>');
                    }
                    else if(item.attr("file_status") == "0"){
                        html.push('<li><i class="fl">文件状态：</i>'+
                                        '<a href="javascript:;" class="fr" onclick="parent.window.Main.Core.Upload.ReuploadByPickCode('+"'" + item.attr("pick_code") + "'"+')">待续传</a>'+
                                        '</li>');
                    }
                    else{
                        html.push('<li><i class="fl">文件状态：</i><span class="fr" style="color:green;">正常</span></li>');
                    }
                   if(item.attr("file_gps")){
                         getAddress(item.attr("file_gps"));
                        //alert($("#filelocation").html());
                        html.push('<li><i class="fl">位置信息：</i><span class="fr" id="filelocation">'+ '' + '</span></li>');
                    }
                    html.push('<li><i class="fl">文件大小：</i><span class="fr">' + Util.File.ShowSize(Number(item.attr("file_size"))) + '</span></li>');

					item.attr("user_ptime") && html.push('<li><i class="fl">创建时间：</i><span class="fr">' + item.attr("user_ptime") + '</span></li>');

//                    html.push('<li><i class="fl">提取码：<a title="进入分享页" href="' + downURI+'/file/'+item.attr("pick_code") + '" target="_blank">' + item.attr("pick_code") + '</a></i>'+
//                        ((item.attr("is_share") == "1") ?'<a href="javascript:;" class="fr" pick_code="' + item.attr("pick_code") + '" title="复制分享地址">复制地址</a>' : "")+
//                        '</li>');
                    
                    if(item.attr("is_share") == "1"){
                        html.push('<li><i class="fl">分享状态：<i style="color:green;">已分享</i></i> '+
                            (is_frumn?"" : '<span class="fr"><a href="javascript:;" menu="cancelshare">取消分享</a></span>')+
                            '</li>');
                    }
                    
					if(item.attr("is_share") == "1"){
						html.push('<li><i class="fl">有效期：</i><span class="fr" detail="pick_expire">' + item.attr("pick_expire") + '</span></li>');
						
					}

                    if(item.attr("is_share") == "1" && item.attr("load_data") == "1"){
                        if(item.attr("is_collect")){
                            if(item.attr("is_collect") == "1"){
                                html.push('<li><i class="fl">转存设置：</i><span class="fr"><i style="color:green;">允许</i> '+
                                            (is_frumn?"" : '<a href="javascript:;" menu="close_share">关</a>')+'</span></li>');
                            }
                            else{
                                html.push('<li><i class="fl">转存设置：</i><span class="fr"><i style="color:red">不允许</i> '+
                                    (is_frumn?"" : '<a href="javascript:;" menu="open_share">开</a>')+'</span></li>');
                            }
                        }
                        
                        if(item.attr("has_pass") == "1"){
                            html.push('<li><i class="fl">访问密码:</i>'+
                                        '<span class="fr"><i style="color:green;">已启用</i>'+
                                        (is_frumn ? "" : ' <a href="javascript:;" menu="privacy">设置</a>')+
                                        '</span></li>');
                        }
                        else{
                            html.push('<li><i class="fl">访问密码:</i>'+
                                        '<span class="fr"><i>未启用</i>'+
                                        (is_frumn?"" : ' <a href="javascript:;" menu="privacy">设置</a>')+
                                        '</span></li>');
                        }
                        
                    }
                    html.push('</ul>');

                    html.push('</div>');
                    
                    
                    if(CheckHasDesc()){
//                        html.push('<div class="file-description">');
//                        html.push('<h3><a href="javascript:;" class="icon ico-account" btn="edit">修改</a>文件备注：</h3>');
//                        var desc = item.find("[field='desc']").val();
//                        if(desc == ""){
//                            html.push('<div class="con" detail="desc">暂无描述</div>');
//                        }
//                        else{
//                            html.push('<div class="con" style="word-wrap:break-word;" detail="desc">' + Util.Text.Cut(desc.replace(/\[.*?\]/g, ""), 50) +'</div>')
//                        }
//                        html.push('</div>');
                    }
					box.html(html.join(''));
                    if(CheckHasDesc()){
//                        box.find('[pick_code]').bind("click", {filename: item.find('[field="file_name"]').attr("title")}, function(e){
//                            Util.Copy(downURI + "/file/" + $(this).attr("pick_code") + '#\r\n' + e.data.filename); 
//                        })
//                        box.attr("file_id", item.attr("file_id"));
//
//                        if(item.attr("load_data") == "1"){
//                            box.find("[btn='edit']").bind("click", {title: item.find('[field="file_name"]').attr("title"), desc: desc, file_id: item.attr("file_id")} ,function(e){
//                                ShowDescBox(e.data.file_id, e.data.title, e.data.desc);
//                            }).show();
//                        }
//                        else{
//                            box.find("[btn='edit']").hide();
//                            box.find("[detail='desc']").html("正获取文件备注...");
//                            _loadDetailTimer = window.setTimeout(function(){
//                                if(_loadDetailTimer){
//                                    window.clearTimeout(_loadDetailTimer);
//                                }
//                                parent.window.Main.Core.FileAjax.GetFileDetail(item.attr("file_id"), function(data){
//                                    item.attr("load_data", "1");
//                                    var desc = data.file_description;
//                                    item.find("[field='desc']").val(desc);
//                                    item.attr("pick_expire", data.pick_time);
//                                    item.attr("is_collect", data.is_collect);
//                                    if(box.attr("file_id") == data.file_id){
//                                        if(item.attr("is_share") == "1"){
//                                            if(data.file_answer != ""){
//                                                item.attr("has_pass", "1");
//                                                item.attr("file_pwd", data.file_answer);
//                                                item.find("[field='ext3']").val(data.file_question);
//                                            }
//                                        }
//                                    }
//                                    ShowRightSide(arr);
//                                });
//                            }, 500);
//                        }
                    }
					break;
				case "0":
					//选择了一个文件夹
					html.push('<div class="file-info">');

					if(item.attr('img_url')){
						html.push('<div class="thumb-cover"><span class="con"><img src="'+item.attr('img_url')+'" ><i></i></span></div>');
					}
					else{
						html.push('<div class="file-thumb tb-folder">'+ ((item.attr("is_share") == "1")? '<b class="shared"></b>': '') + '</div>');
					}
					html.push('<div class="thumb-name">'+item.attr("cate_name")+'</div>');
                    
                    
                    html.push('<div class="btn-container"><span class="btn-wrap">'+   
//                                    (item.attr("is_share") == "1"? '<a href="'+downURI + "/folder/" + item.attr("pick_code")+'" target="_blank" class="btn">打开</a>' :'<a href="javascript:;" class="btn" menu="shareto">分享</a>') +
                                     '<a href="javascript:;" class="btn" menu="edit_name">重命名</a>'+   
                              '</span></div>');
                    
					html.push('<ul detail="ext_feild">');

					if(item.attr("is_share") == "1"){
//						html.push('<li detail="pick_code">'+
//                                    '<i class="fl">提取码：<a title="进入分享页" href="' + downURI+'/folder/'+item.attr("pick_code") + '" target="_blank">'+ item.attr("pick_code")+'</a></i>'+
//                                        '<a href="javascript:;" class=" fr" pick_code="'+item.attr("pick_code")+'" title="复制分享地址">复制地址</a></li>');
//                        html.push('<li><i class="fl">分享状态：<i style="color:green;">已分享</i></i> '+
//                            (is_frumn?"" : '<span class="fr"><a href="javascript:;" menu="cancelshare">取消分享</a></span>') +
//                            '</li>');
					}
                    var ptime = "-";
                    if(item.attr("ptime")){
                        ptime = item.attr("ptime");
                    }
                    html.push('<li><i class="fl">创建时间：</i><span class="fr" detail="ptime">' + ptime + '</span></li>');

					var coverLink = "";
					if(dataSource.aid == 3 || dataSource.aid == 4){
//						html.push('<li><i class="fl">编辑封面：</i>'+
//                                        '<span class="fr">'+
//                                            '<a href="javascript:;" class="icon ico-cover" rel="edit_cover" title="编辑封面">编辑</a>'+
//                                        '</span></li>');
					}

                    if(item.attr("load_data") == "1"){
                        if(item.attr("category_file_count")){
                            html.push('<li><i class="fl">包含:</i><span class="fr">' + item.attr("category_file_count") + '个文件</span></li>');
                        }
                        
                        if(item.attr("is_share") == "1"){
                            if(item.attr("has_pass") == "1"){
                                html.push('<li><i class="fl">访问密码:</i>'+
                                            '<span class="fr"><i style="color:green;">已启用</i>'+
                                            (is_frumn?"":' <a href="javascript:;" menu="privacy">设置</a>')+
                                            '</span></li>');
                            }
                            else{
                                html.push('<li><i class="fl">访问密码:</i>'+
                                            '<span class="fr"><i>未启用</i>'+
                                            ' <a href="javascript:;" menu="privacy">设置</a></span></li>');
                            }
                        }
                        
                    }
                    

					html.push('</ul>');
                    
					html.push('</div>');
					box.html(html.join(''));
                    box.attr("cate_id", item.attr("cate_id"));
					box.find('[pick_code]').bind("click", {catename: item.attr("cate_name")},function(e){
						Util.Copy(downURI + "/folder/" + $(this).attr("pick_code") + '#\r\n' + e.data.catename);
					})
					box.find("[rel='edit_cover']").bind("click", {cid: item.attr("cate_id")}, function(e){
						// 编辑封面
                        parent.window.Main.Core.FileSelectDG.EditCover(dataSource.aid, e.data.cid);
					})
                    
                    if(item.attr("load_data") != "1"){
                        _loadDetailTimer = window.setTimeout(function(){
                            if(_loadDetailTimer){
                                window.clearTimeout(_loadDetailTimer);
                            }
                            parent.window.Main.Core.FileAjax.GetDirDetail(item.attr("area_id"), item.attr("cate_id"), function(data){
                                //category_file_count
                                item.attr("category_file_count", data.category_file_count);
                                item.attr("load_data", "1");
                                item.attr("ptime", data.ptime);
                                item.attr("pick_code", data.pick_code);
                                
                                if(data.is_share == "1"){
                                    
                                    if(data.password != ""){
                                        item.attr("has_pass", "1");
                                        item.attr("file_pwd", data.password);
                                        item.find("[field='ext3']").val(data.ext3);
                                    }
                                }
                                
                                ShowRightSide(arr);
                            })
                        })
                    }
                    
					break;
			}

		}
		else{

			//选择了多个文件
			html.push('<div class="file-info">');
       		html.push('<div class="file-thumb multi-files"></div>');
            
			var sharedResult = true;
			var urls = [];
            var fileCount = 0;
            var folderCount = 0;
            var fileSize = 0;
			for(var i = 0, len = arr.length; i < len; i++){
				var item = arr[i];
                if(item.attr("file_type") == "1"){
                    fileCount++;
                    fileSize += Number(item.attr("file_size"));
                }
                else if(item.attr("file_type") == "0"){
                    folderCount++;
                }
                
                
				//判断是否是已分享
				if(item.attr("is_share") != "1"){
					sharedResult = false;
				}
				else{
					if(item.attr("file_type") == "1"){
						urls.push(downURI + '/file/' + item.attr("pick_code") + '#\r\n' + item.find('[field="file_name"]').attr("title"));
					}
					else{
						urls.push(downURI + '/folder/' + item.attr("pick_code") + '#\r\n' + item.attr("cate_name"));
					}
				}
			}

            html.push('<div class="thumb-name">已选中 ' + arr.length + ' 条记录</div>');
            
            if(!folderCount && fileCount){
                // 加操作按钮
                var addBtn = '';
                switch(dataSource.aid){
                    case 2:
                        addBtn = '<a href="javascript:;" class="btn" menu="view_doc">预览</a>';
                        break;
                    case 3:
                        addBtn = '<a href="javascript:;" class="btn" menu="view_photo">预览</a>';
                        break;
                    case 4:
                        addBtn = '<a href="javascript:;" class="btn" menu="view_music">试听</a>';
                        break;
                }
                
                html.push('<div class="btn-container">'+
                              '<span class="btn-wrap">'+
//                                (document.all ? '<a href="javascript:;" class="btn" menu="download">下载</a>' : '')+ addBtn +
//                                (sharedResult ? '<a href="javascript:;" class="btn" menu="renew">续期</a>' : 
//                                '<a href="javascript:;" class="btn" menu="shareto">分享</a>')+
                              '</span>'+
                          '</div>');
            }
            

            
            html.push('<ul>');
            html.push('<li><span class="fr">'+
                        (folderCount? folderCount + "个文件夹" : "") +
                        (folderCount && fileCount? "," : "")+
                        (fileCount? " " + fileCount + "个文件 " + Util.File.ShowSize(fileSize) : "") +
                        '</span></li>');
			if(sharedResult){
                html.push('<li><i class="fl">分享状态：<i style="color:green;">已分享</i></i> '+
                    (is_frumn?"": '<span class="fr"><a href="javascript:;" menu="cancelshare">取消分享</a></span>')+
                    '</li>');
				html.push('<li>'+
                                '<a class="fr" href="javascript:;" rel="copy_btn" title="复制分享地址">复制分享地址</a>'+
                          '</li>');
			}
            html.push('</ul>');

			html.push('</div>');
			box.html(html.join(''));
			box.find('[rel="copy_btn"]').bind("click", {urls:urls}, function(e){
				Util.Copy(e.data.urls.join("\n"));
				return false;
			})
            
		}
        
	}
    else{
        _pageShowFreeTimer = window.setTimeout(function(){
            ShowFreeMsg();
        }, 100)
    }
}

var PageCheckCTL = {
    checkAllNode: function(){
        if(dataList.length){
            dataList.find("input:checkbox").attr("checked", true);
            var arr = [];
            dataList.each(function(i){
                var ele = $(this);
                if(!ele.hasClass("focus") && ele.find("input:checkbox").length){
                    ele.addClass("focus");
                }
                arr.push(ele);
            })
            if(arr.length){
                page_cache.list = arr;
                PageCheckCTL.checkSelectBox(arr, false);
            }
            else{
                page_cache.list = false;
                PageCheckCTL.checkSelectBox(false);
            }
        }
    },
    checkSelectBox: function(arr, e, is_no_allcheck){
        if(!is_no_allcheck){
            $("input[check='all']").attr("checked", false);
        }
        for(var i = 0,len = arr.length; i < len; i++){
            var item = arr[i];
            var checkbox = item.find("input[type='checkbox']");
            checkbox.attr("checked",true);
        }

        ShowRightSide(arr);

        if(FileCheckHandler){
            if(_showMenuTimer){
                window.clearTimeout(_showMenuTimer);
            }
            _showMenuTimer = window.setTimeout(function(){
                e ? FileCheckHandler(arr, e.screenX + 10, e.clientY - 35) : FileCheckHandler(arr);
            },20);
        }
    },
	checkItemCol: function(e){
		if(e.target.nodeName == "INPUT"){
			return true;
		}
		if($(e.target).attr("menu") == "star"){
			TopMenu.doClick($(e.target));
			return true;
		}
		if(dataList.length){
            //$(this).attr("checked", this.checked);
			var input = $(this).find("input:checkbox");
            var par = $(this).parents('[rel="item"]');
			input.attr("checked", !input.attr("checked"));
            if(input.attr("checked")){
                !par.hasClass("focus") && par.addClass("focus");
            }
            else{
                par.hasClass("focus") && par.removeClass("focus");
            }

            var arr = [];
            dataList.find("input:checked").each(function(i){
                arr.push($(this).parents("[rel='item']"));
            });

            if(arr.length){
                page_cache.list = arr;
            }
            else{
                page_cache.list = false;
            }
            PageCheckCTL.checkSelectBox(page_cache.list,e);
        }
	},
    checkItemCheckBox: function(e){
        if(dataList.length){
            //$(this).attr("checked", this.checked);
            var par = $(this).parents('[rel="item"]');
            if(this.checked){
                !par.hasClass("focus") && par.addClass("focus");
            }
            else{
                par.hasClass("focus") && par.removeClass("focus");
            }

            var arr = [];
            dataList.find("input:checked").each(function(i){
                arr.push($(this).parents("[rel='item']"));
            });

            if(arr.length){
                page_cache.list = arr;
            }
            else{
                page_cache.list = false;
            }
            PageCheckCTL.checkSelectBox(page_cache.list,e);
        }
    },
    checkShowNoFile: function(){
        if(!dataList.length){
            window["interface"].ShowNoFile && window["interface"].ShowNoFile();
        }
        else{
            window["interface"].HideNoFile && window["interface"].HideNoFile();
        }
    }
}

//数据控制器
var DataCTL = {
	_is_loading: false,
	_is_last: false,
	_offset: dataSource.next_offset,	//游标
	_last_params: "",
	_aid: dataSource.aid,
	_cid: dataSource.cid,
    GetFileOffset: function(file_id){
        if(!window.IsTempLoad){
            if(dataList.length > 200){
                var limit = Number(dataSource.limit);
                var s = 0;
                for(var i = 0, len = dataList.length; i < len; i++){
                    if(i > 0 && (i % limit) == 0){
                        s++;
                    }
                    var item = $(dataList[i]);
                    if(Number(file_id) == Number(item.attr("file_id"))){
                        return s * limit;
                    }
                }
                return 0;
            }
            else{
                return 0;
            }
        }
        else{
            if(window.location.search.indexOf("&s=") != -1){
                var s = window.location.search.replace(/^.*&s=/, "");
                s = s.replace(/&.*$/, "");
                return Number(s);
            }
            else{
                return 0;
            }
        }
    },
	UpdateDataList: function(){
		dataList = $("[rel='list'] [rel='item']");
		$("a").unbind("mousedown").bind("mousedown",function(e){
			page_stopPropagation(e);
		})
		dataList.each(function(i){
			var dom = $(this);
			dom.find("input:checkbox").mousedown(function(e){
				page_stopPropagation(e);
				return true;
			}).mouseup(function(e){
				page_stopPropagation(e);
				return true;
			}).click(PageCheckCTL.checkItemCheckBox);
			dom.find(".file-check").mousedown(function(e){
				page_stopPropagation(e);
				return true;
			}).mouseup(function(e){
				page_stopPropagation(e);
				return true;
			}).click(PageCheckCTL.checkItemCol);
		});
	},
	//更新文件信息
	UpdateFile: function(obj){
		var item = $('[file_id="' + obj.file_id + '"]');
		if(item.length){
			if(obj.file_name){
				item.find("[field='file_name']").attr("title", obj.file_name).html(obj.file_name);
			}
			if(obj.desc){
				item.find("[field='desc']").val(obj.desc);
			}

			ShowRightSide([item]);	//显示右边信息栏
		}
	},
    UpdateDir: function(obj){
        
        var item = $('[rel="item"][cate_id="' + obj.cid + '"]');
        
		if(item.length){
			item.attr("cate_name", obj.dir_name);
            if(obj.dir_name){
				item.find("a[cid='"+obj.cid+"']").attr("title", obj.dir_name).html(obj.dir_name);
			}
			ShowRightSide([item]);	//显示右边信息栏
		}
    },
	ShareOne: function(aid, cid, type, tid, dataType){
		if(aid != DataCTL._aid || cid != DataCTL._cid){
			return;
		}
		var list;
		if(dataType == 0){
			list = outer.find("[file_type='" + dataType + "'][cate_id='" + tid + "']");
		}
		else{
			list = outer.find("[file_type='" + dataType + "'][file_id='" + tid + "']");
		}
		var arr = [];
		list.each(function(i){
			arr.push($(this));
		})
		DataCTL.Share(aid, cid, type, arr);
	},
	Share: function(aid, cid, type, list){
		if(aid != DataCTL._aid || cid != DataCTL._cid){
			return;
		}
		for(var i = 0, len = list.length; i < len; i++){
			var item = list[i];

			switch(type){
				case 2:
				case 1:
					window["interface"].Share && window["interface"].Share(item);
					break;
				case 0:
					window["interface"].CancelShare && window["interface"].CancelShare(item);
					break;
			}
		}

		ShowRightSide(list);	//显示右边信息栏
	},
    Privacy: function(aid, cid, setting, list){
        if(aid != DataCTL._aid || cid != DataCTL._cid){
			return;
		}
		for(var i = 0, len = list.length; i < len; i++){
			var item = list[i];

			window["interface"].Privacy && window["interface"].Privacy(setting, item);
		}

		ShowRightSide(list);	//显示右边信息栏
    },
    GetDir: function(cid){
        var listBox = $("[rel='list']");
        var list = listBox.find("[file_type='0'][cate_id='"+cid+"']");
        if(list.length == 1){
            return $(list[0]);
        }
        return false;
    },
    AllowCollect: function(aid, cid, is_collect, list){
        if(aid != DataCTL._aid || cid != DataCTL._cid){
			return;
		}
		for(var i = 0, len = list.length; i < len; i++){
			var item = list[i];
			window["interface"].AllowCollect && window["interface"].AllowCollect(is_collect, item);
		}

		ShowRightSide(list);	//显示右边信息栏
    },
	DelOne: function(aid, cid, tid, dataType){
		if(aid != DataCTL._aid || cid != DataCTL._cid){
			return;
		}
		var list;
		if(dataType == 0){
			list = outer.find("[file_type='" + dataType + "'][cate_id='" + tid + "']");
		}
		else{
			list = outer.find("[file_type='" + dataType + "'][file_id='" + tid + "']");
		}
		var arr = [];
		list.each(function(i){
			arr.push($(this));
		})
		DataCTL.Del(aid, cid, arr);
	},
	Del: function(aid, cid, list){
		if(aid != DataCTL._aid || cid != DataCTL._cid){
			return;
		}
        if(window.IsTempLoad){
            DataCTL.Reload(aid,cid);
            return;
        }
		for(var i = 0, len = list.length; i < len; i++){
			var item = list[i];
			item.empty().remove();
		}
		dataList = $("[rel='list'] [rel='item']");
		PageCheckCTL.checkSelectBox(false);
		ShowRightSide(false);
		PageCheckCTL.checkShowNoFile();
		if(!dataList.length){
			window.location.reload();
		}
	},
	_bindDblclick: function(itemNode){
        if(itemNode.attr("file_status") == "0"){
            parent.window.Main.Core.Upload.ReuploadByPickCode(itemNode.attr("pick_code"));
            return;
        }
        if(itemNode.attr("file_status") == "2"){
            return;
        }
        if(window["PAGE_IS_API"]){
            window["DBLClick_BACK"] && window["DBLClick_BACK"](itemNode);
            return;
        }
		var ele = itemNode.find('[rel="view_folder"]');
		if(ele.length){
			var ele = itemNode.find("[btn='goto_dir']");
            parent.window.PageCTL.SelectNode(ele.attr("aid"), ele.attr("cid"));
            parent.window.PageCTL.GOTO(ele.attr("aid"), ele.attr("cid"));
			return;
		}
		ele = itemNode.find('[rel="photo"]');
		if(ele.length){
		    var start   = itemNode.attr('s');
            var limit   = itemNode.attr('limit');
			var file_id = itemNode.attr("file_id");
			var ids     = itemNode.attr("ids");
            //显示图片
			parent && parent.window.Main.Core.PhotoView.Show(dataSource.aid, dataSource.cid,file_id, itemNode.attr("is_online"), start, limit, ids);
			return;
		}
		ele = itemNode.find('[rel="music"]');
		if(ele.length){
			var addList = [];
			addList.push({name: itemNode.find('[field="file_name"]').attr("title"), mp3: itemNode.attr("path")});
            //打开音乐
			parent && parent.window.Main.Core.MusicPlayer.Add(addList, true);
			return;
		}
        ele = itemNode.find('[rel="document"]');
		if(ele.length){
            // 阅读文档

            parent && parent.window.Main.Core.Reader.Open(itemNode.attr("pick_code"));

			return;
		}
        
        ele = itemNode.find('[rel="file"]');
        if(ele.length){
            // 下载文件
            parent && parent.window.Main.Core.FileAPI.Download(itemNode.attr("pick_code"));;

			return;
		}
	},
	//绑定事件
	_bindNode: function(dom){
        dom.find(".network-continue").bind("mousedown", function(e){
             page_stopPropagation(e);
            var el = $(this);
            var itemNode = el.parents("[rel='item']")
            parent.window.Main.Core.Upload.ReuploadByPickCode(itemNode.attr("pick_code"));
            return false;
        });
        if(dom.attr("file_status") == "0"){
            dom.attr("title", "文件未上传完成，双击续传");
        }
        else if(dom.attr("file_status") == "2"){
            dom.attr("title", "文件正在进入云端，请稍后访问。");
        }
		dom.bind("dblclick", function(e){
			var itemNode = $(this);
			DataCTL._bindDblclick(itemNode);
		}).bind("contextmenu", function(e){
            if(!FileRightHandler) return;
            
            page_stopPropagation(e);
            var arr = [];
            if($(this).hasClass("focus")){
                //操作
                $("[rel='item'].focus").each(function(i){
                    arr.push($(this));
                })

            }
            else{
                $("[rel='item'].focus").removeClass("focus").find("input:checkbox").attr("checked",false);
                arr.push($(this).addClass("focus"));
                page_cache.list = [$(this)];
                page_cache.oldchecks = arr;
            }
            PageCheckCTL.checkSelectBox(arr);
            FileRightHandler && FileRightHandler(arr, e.clientX, e.clientY);
            return false;
		}).bind("mousedown", function(e){
            if(e.button == 2){
				if(!FileRightHandler) return;
				page_stopPropagation(e);
                return false;
            }
        })
        //.bind("contextmenu", function(e){ return false; });
		dom.find("a").mousedown(function(e){
			page_stopPropagation(e);
		}).click(function(){
            var el = $(this);
            var itemNode = el.parents("[rel='item']")
            if(itemNode.attr("file_status") == "0"){
                parent.window.Main.Core.Upload.ReuploadByPickCode(itemNode.attr("pick_code"));
                return false;
            }
            else if(itemNode.attr("file_status") == "2"){
                parent.window.Main.Core.MinMessage.Show({text: "文件正在进入云端，请稍后访问。", type: "war", timeout: 2000});
                return false;
            }
            if(el.attr("rel")){
                switch($(this).attr("rel")){
                    case "photo":
                        var start   = itemNode.attr('s');
                        var limit   = itemNode.attr('limit');
                        var file_id = itemNode.attr("file_id");
                        var ids     = itemNode.attr("ids");
                        //打开图片
                        parent && parent.window.Main.Core.PhotoView.Show(dataSource.aid, dataSource.cid,file_id, $(this).attr("is_online"), start, limit, ids);
                        break;
                    case "music":
                        var addList = [];
                        addList.push({name: itemNode.find('[field="file_name"]').attr("title"), mp3: itemNode.attr("path")});
                        //打开音乐
                        parent && parent.window.Main.Core.MusicPlayer.Add(addList, true);
                        break;
                    case "document":
                        var pick_code = itemNode.attr("pick_code");
                        parent && parent.window.Main.Core.Reader.Open(pick_code);
                        break;
                    case "file":
                        var pick_code = itemNode.attr("pick_code");
                        parent.window.Main.Core.FileAPI.Download(pick_code);
                        break;
                    default:
                        return true;
                }
                return false;
            }
		})

		dom.find("input:checkbox").attr("checked",false);
	},
	Add: function(arr){
		var html = window["interface"].GetHtml(arr);
		var dom = $(html.join(''));
		$("[rel='list']").append(dom);
		DataCTL._bindNode(dom);
		dom.find("input:checkbox").mousedown(function(e){
			page_stopPropagation(e);
			return true;
		}).mouseup(function(e){
			page_stopPropagation(e);
			return true;
		}).click(PageCheckCTL.checkItemCheckBox);
		dom.find(".file-check").mousedown(function(e){
			page_stopPropagation(e);
			return true;
		}).mouseup(function(e){
			page_stopPropagation(e);
			return true;
		}).click(PageCheckCTL.checkItemCol);
		dataList = $("[rel='list'] [rel='item']");

		PageCheckCTL.checkShowNoFile();
	},
	Reload: function(aid, cid){
		if(aid != undefined && cid != undefined){
			if(aid != DataCTL._aid || cid != DataCTL._cid) return;
		}
		window.location.reload();
	},
	AddOne: function(data){
		if(data.area_id != DataCTL._aid || data.category_id != DataCTL._cid){
			return;
		}
		var html = window["interface"].GetHtml([data]);
		var dom = $(html.join(""));
		var first;
		if(data.file_id){
			first = $("[rel='list'] [file_type='1']:first");
		}
		else{
			first = $("[rel='list'] [file_type='0']:first");
		}
		if(first.length){
			first.before(dom);
		}
		else{
			$("[rel='list']").append(dom);
		}
		dom.find("input:checkbox").mousedown(function(e){
			page_stopPropagation(e);
			return true;
		}).mouseup(function(e){
			page_stopPropagation(e);
			return true;
		}).click(PageCheckCTL.checkItemCheckBox);
		dom.find(".file-check").mousedown(function(e){
            page_stopPropagation(e);
			return true;
        }).mouseup(function(e){
            page_stopPropagation(e);
			return true;
        }).click(PageCheckCTL.checkItemCol);
		
		DataCTL._bindNode(dom);
		dataList = $("[rel='list'] [rel='item']");
		PageCheckCTL.checkShowNoFile();
	},
	LoadData: function(){
		if(DataCTL._is_last){
			return;
		}
		if(DataCTL._is_loading){
			return;
		}

		DataCTL._is_loading = true;
		$("#j_start").hide();
		$("#j_loading").show();
		$("#j_error").hide();

		var url = PAGE_PATHS["MY"]+"index.php?ct=file&ac=userfile&tpl=list&ajax=1&aid="+DataCTL._aid + "&cid=" + DataCTL._cid +"&s=" + DataCTL._offset + "&" + DataCTL._last_params;
		if(dataSource){
			if(dataSource.filter != undefined){
				url += "&f=" + dataSource.filter
			}
			if(dataSource.is_asc != undefined){
				url += "&a=" + dataSource.is_asc
			}
			if(dataSource.order != undefined){
				url += "&o=" + dataSource.order
			}
		}
		$.ajax({
			url: url,
			type: "GET",
			dataType: "json",
			cache: false,
			success: function(r){
				$("#j_start").show();
				$("#j_loading").hide();
				if(r.data){
					DataCTL.Add(r.data);

					DataCTL._offset = r.next_offset;
					DataCTL._is_loading = false;
					if(DataCTL._offset >= r.count){
						DataCTL._is_last = true;
                        if(innerBox.height() < outer.height()){
                            innerBox.height(outer.height());
                        }
						$("#j_start").hide();
                        if(!$("#js_cantain_box").find(".file-pages").length){
                            $("#js_cantain_box").append('<div class="file-pages"></div>');
                        }
					}
				}
			},
			error: function(){
				DataCTL._is_loading = false;
				$("#j_error").show();
				$("#j_loading").hide();
			}
		})
	}
}

//显示修改描述窗口
var ShowDescBox = function(file_id, title, desc){
    if(!TopMenu.CheckButtonIsDo("edit")) return;
    //修改文件描述
	if(parent && parent.window.Main.Core.FileDescDG){
		parent.window.Main.Core.FileDescDG.Show({aid: DataCTL._aid, file_id: file_id, title: title, value: desc});
	}
}

var LoadTemplete = function(){
    //判断是否是模板输出
    if(!window.IsTempLoad){
        if(DataCTL._offset >= dataSource.count){

            DataCTL._is_last = true;
            $("#j_start").hide();
            $("#js_cantain_box").removeClass("pages-container");
        }

        $("#j_error").mousedown(function(e){
            page_stopPropagation(e);
            DataCTL.LoadData();
        })

        $("#j_start").mousedown(function(e){
            page_stopPropagation(e);
            DataCTL.LoadData();
        })

        //滚动条移动事件
        $("#js_data_list_outer").bind("scroll", function(){
            checkDowload();
        })

        var checkDowload = function(){
            //判断是否要加载数据
            if(DataCTL._is_last){
                $("#j_start").hide();
                if(!$("#js_cantain_box").find(".file-pages").length){
                    $("#js_cantain_box").append('<div class="file-pages"></div>');
                }
                return;
            }
            var ele = $("#js_data_list_outer");
            var st = ele[0].scrollTop;
            var sh = ele[0].scrollHeight - ele.height();
            if((sh - sh/10) < st || sh == 0){
                //获取数据
                DataCTL.LoadData();
            }
        }

        DataCTL.Add(dataSource.data);

        checkDowload();
        if(DataCTL._is_last){
            if(innerBox.height() < outer.height()){
                innerBox.height(outer.height());
                $(window).bind("resize", function(){
                    innerBox.height(outer.height());
                })
            }
        }
    }
    else{
        dataList = $("[rel='list'] [rel='item']");

        dataList.each(function(){
            var dom = $(this);
            DataCTL._bindNode(dom);
            dom.find("input:checkbox").mousedown(function(e){
                page_stopPropagation(e);
                return true;
            }).mouseup(function(e){
                page_stopPropagation(e);
                return true;
            }).click(PageCheckCTL.checkItemCheckBox);

            dom.find(".file-check").mousedown(function(e){
                page_stopPropagation(e);
                return true;
            }).mouseup(function(e){
                page_stopPropagation(e);
                return true;
            }).click(PageCheckCTL.checkItemCol);
        })

        $("a").mousedown(function(e){
            page_stopPropagation(e);
        })
        if(innerBox.height() < outer.height()){
            innerBox.height(outer.height());
            $(window).bind("resize", function(){
                innerBox.height(outer.height());
            })
        }
    }
}

LoadTemplete();

var _SQInnerBox;
var SquareResize = function(x, y, eX, eY, isctrl){
	if(!isctrl){page_cache.list = [];}	//清空旧列表
	if(!page_cache.list){page_cache.list = [];}

    var innerW = innerBox.width();
    var paddingW = Number(_SQInnerBox.css("padding-left").replace("px", "")) + Number(_SQInnerBox.css("padding-right").replace("px", ""));
    if(paddingW){
        innerW -= paddingW;
    }

	var wCount = Math.floor(innerW/lineWidth);
    
    
	var h = outer.height();
    var innerTop = outer.offset().top;

	var t = Math.abs(dataList.offset().top - innerTop);
	var start = Math.floor(t/lineHeight);
    if(dataList.offset().top > innerTop){
        start = start - 1;
    }
    if(start<0) start = 0;
	start = start * wCount;

	var end = h%lineHeight? Math.floor(h/lineHeight)+1 : Math.floor(h/lineHeight);
	end = (end + 1) * wCount;
	end = start + end;


	if(end >= dataList.length){
		end = dataList.length;
	}

	var idsStr = {};
	for(var j = 0, len = page_cache.list.length; j < len; j++){
		var ind = $(page_cache.list[j]).attr("index");
		if(ind != undefined){
			idsStr[$(page_cache.list[j]).attr("index")] = true;
		}
	}
	for(var i = start, len = end; i< len; i++){
		var item = $(dataList[i]);
        if(item.offset().top - item.height() - innerTop){
            if(Number(item.attr("index")) != i){
                item.attr("index",i);
                page_cache.list.push(dataList[i]);
            }
            else{
                var hasItem = idsStr[i.toString()];
                if(!hasItem){
                    page_cache.list.push(dataList[i]);
                }
            }
        }
	}


	for(var i = 0, len = page_cache.list.length; i< len; i++){
		var item = $(page_cache.list[i]);
		if(item.length){
			var tSY = item.offset().top - outer.scrollTop();
			var tEY = tSY + lineHeight;

			var tSX = item.offset().left - outer.scrollLeft();
			var tEX = tSX + lineWidth;
			if( ((tSY < eY && tSY > y) || (tEY > y && tEY < eY) || (tSY < y && tSY < eY && tEY > y && tEY > eY)) && ((tSX < eX && tSX > x) || (tEX > x && tEX < eX) || (tSX < x && tSX < eX && tEX > x && tEX > eX))){
				if(isctrl){
					if(item.hasClass("focus")){
						item.removeClass("focus");
						var input = item.find("input[type='checkbox']");
						input.attr("checked",false);
					}else{
						item.addClass("focus");
					}
				}
				else{
					item.addClass("focus");
				}
			}
			else{
				if(!isctrl){
					item.removeClass("focus");
				}
			}
		}
	}
	PageCheckCTL.checkSelectBox(false);
}

//绑定框选
var PageSquareObj = Util.Mouse.Square(innerBox,outer,{
	mousedown: function(x,y,eX,eY,isctrl){
		//鼠标按下事件
		if(!dataList.length){return;}
        if(!_SQInnerBox){
            _SQInnerBox = $("#js_data_list_inner"); 
        }
		lineHeight = dataList.outerHeight();	//行高
		lineWidth = dataList.outerWidth();	//行宽
		var mr = Number(dataList.css("margin-right").replace("px",""));
		var ml = Number(dataList.css("margin-left").replace("px",""));
		lineWidth = lineWidth + mr + ml;
        
		var mt = Number(dataList.css("margin-top").replace("px",""));
		var mb = Number(dataList.css("margin-bottom").replace("px",""));
		lineHeight = lineHeight + mt + mb;
        
		//移除旧列表样式
		if(!isctrl){
			if(page_cache.list && page_cache.list.length){
                for(var i = 0, len = page_cache.list.length; i< len; i++){
                    var item = $(page_cache.list[i]);
                    item.removeClass("focus");
                    item.find("input[type='checkbox']").attr("checked",false);
                }

			}
		}
		SquareResize(x, y, eX, eY, isctrl);
		page_cache.is_move = false;
	},
	mousemove: function(x, y, eX, eY, isctrl){
		//鼠标经过事件
		if(!dataList.length){return;}
		if(page_cache.list && page_cache.list.length){
			//style="-moz-user-select:none;" onselectstart="return false;"
			innerBox.css("-moz-user-select", "none");
			innerBox.bind("selectstart", function(){return false;});

            page_cache.is_move = true;

			for(var i = 0, len = page_cache.list.length; i< len; i++){
				var item = $(page_cache.list[i]);
				if(item.length){
					var tSY = item.offset().top;
					var tEY = item.offset().top + item.height();
					var tSX = item.offset().left - outer.scrollLeft();
					var tEX = item.offset().left - outer.scrollLeft() + lineWidth;
					if( ((tSY < eY && tSY > y) || (tEY > y && tEY < eY) || (tSY < y && tSY < eY && tEY > y && tEY > eY)) && ((tSX < eX && tSX > x) || (tEX > x && tEX < eX) || (tSX < x && tSX < eX && tEX > x && tEX > eX))){
                        if(!item.hasClass("focus")) item.addClass("focus");
					}
					else{
						if(!isctrl){
//							if(item.hasClass("focus")) item.removeClass("focus");
						}
					}
				}
			}

		}
	},
	mouseup: function(x,y,eX,eY,isctrl, e){
        //alert(x  + " " + eX + " " + e.pageX);
		innerBox.css("-moz-user-select", "");
		innerBox.unbind("selectstart").bind("selectstart", function(){return false;});
		//鼠标起来事件
		if(!dataList.length){return;}
		if(page_cache.list && page_cache.list.length){
			var checkBoxs = [];
			for(var i = 0, len = page_cache.list.length; i< len; i++){
				var item = $(page_cache.list[i]);
				if(item.length && item.hasClass("focus")){
                    if(item.find("input[type='checkbox']").length){
                        checkBoxs.push(item);
                    }
                    else{
                        item.removeClass("focus");
                    }
				}
			}
			if(page_cache.oldchecks && page_cache.oldchecks.length == 1 && checkBoxs.length == 1){
				if(page_cache.oldchecks[0].attr("index") == checkBoxs[0].attr("index")){
					var item = checkBoxs[0];
					var input = item.find("input[type='checkbox']");
					input.attr("checked",false);
					if(input.attr("checked")){
						item.addClass("focus");
						PageCheckCTL.checkSelectBox(checkBoxs, e);
					}
					else{
						item.removeClass("focus");
						PageCheckCTL.checkSelectBox(false);
					}
					page_cache.oldchecks = false;
					return;
				}
				else{
					PageCheckCTL.checkSelectBox(checkBoxs, e);
				}
			}
			else{
				PageCheckCTL.checkSelectBox(checkBoxs, e);

			}
			page_cache.oldchecks = checkBoxs;
		}
	}
});

var PageBindEventFun = function(){
    /*绑定全选CheckBox事件*/
    outer.find("input[check='all']").mousedown(function(e){page_stopPropagation(e);}).click(function(e){
        if(dataList.length){
            dataList.find("input:checkbox").attr("checked", this.checked);
            $("input[check='all']").attr("checked", this.checked);
            var ischeck = this.checked;
            var arr = [];
            dataList.each(function(i){
                var ele = $(this);
                if(ele.find("input:checkbox").length){
                    if(ischeck){
                        !ele.hasClass("focus") && ele.addClass("focus");
                        arr.push(ele);
                    }
                    else{
                        ele.hasClass("focus") && ele.removeClass("focus");
                    }
                }
            })
            if(arr.length){
                page_cache.list = arr;
                PageCheckCTL.checkSelectBox(arr,e, true);
            }
            else{
                page_cache.list = false;
                PageCheckCTL.checkSelectBox(false);
            }
        }
    })

    /*绑定排序*/
    var listInnerBox = $("#js_data_list_inner");
    listInnerBox.find("[order]").mousedown(function(e){
        if($.browser.msie){
            event.cancelBubble=true;
        }else{
            e.stopPropagation();
            e.preventDefault();
        }	//停止冒泡
        return true;
    }).click(function(e){
        if($.browser.msie){
            event.cancelBubble=true;
        }else{
            e.stopPropagation();
            e.preventDefault();
        }	//停止冒泡
        var ele = $(this);
        var a = ele.find(".arrow");
        if(a.length){
            Util.Url.ReplaceQueryVar("a", a.hasClass("asc-order")? 0 : 1);
        }
        else{
            Util.Url.ReplaceQueryVar("o", ele.attr("order"));
        }
        return false;
    })
    
    //加载浮动头部
    if(listInnerBox.addClass(".file-list")){
        var dt = listInnerBox.find("dt");
        var ul = dt.find("ul").clone(true);
        ul.addClass("title-float title-star").hide();
        ul.find("#js_datalist_check_all").attr("id", "js_datalist_check_all2");
        ul.find("label[for='js_datalist_check_all']").attr("for", "js_datalist_check_all2");
        
        if(!listInnerBox.hasClass("list-star")){
            
            ul.find("li.file-check").css("width", "36px");
            ul.find("li.file-name").css("left", "36px");
        }
        
        $(document.body).append(ul);
        
        var outerBox = $("#js_data_list_outer");
        if(outerBox.length){
        ul.css({
            width:dt.width(),
            top: outerBox.offset().top + 1
        })
        outerBox.bind("scroll", function(){
            if(ul.width() != dt.width()){
                ul.css({
                    width:dt.width()

                })
            }
            if(outerBox.scrollTop()){
                ul.show();
            }
            else{
                ul.hide();
            }
        })
        }
    }

    /*绑定Document事件*/
    $(document).bind("keydown", function(e){
        if(e.ctrlKey){
            if(e.keyCode == 65){
                PageCheckCTL.checkAllNode();
                return false;
            }
        }
    })

    $(document).click(function(e){
        var ele = $(e.target);
        var par = ele.parents("[rel='item']");
        switch(ele.attr("btn")){
            case "goto_dir":
                // 打开目录
                parent.window.PageCTL.SelectNode(ele.attr("aid"), ele.attr("cid"));
                parent.window.PageCTL.GOTO(ele.attr("aid"), ele.attr("cid"));
                return false;
        }
    })

    $(document).bind("selectstart", function(){return PageDocumentSelectState;});
    $(".col-sub").bind("mousedown", function(e){
        PageDocumentSelectState = true;
    }).bind("mouseup", function(e){
        PageDocumentSelectState = false;
    })
}

var PageInitFun = function(){

    if(!NotPutAPI && parent){
        
        var cid = dataSource.cid;
        if(cid == 0){
            cid = dataSource.aid + "_0";
        }
        
        //选中打开的目录
        parent.window.PageCTL.SelectNode(dataSource.aid, dataSource.cid);

        //获取面包屑
        var backAid = -1, backCid = -1;
        
        var htmlArr = [];
        htmlArr.push('<a href="javascript:;" btn="goto_dir" aid="-1" cid="-1">首页</a>');
        if(!window["LIST_CONFIG"]){
            LIST_CONFIG = {};
        }
        LIST_CONFIG.active = {aid: dataSource.aid, cid: dataSource.cid};
        if(LIST_CONFIG.top_tip && LIST_CONFIG.top_tip.length){ 
            var pars = LIST_CONFIG.top_tip;
            if(pars && pars.length){

                for(var i = 0, len = pars.length; i < len; i++){
                    var item = pars[i];
                    if(item){
                        var cidTxt = item.cid.toString();
                        if(i == len - 1){
                            LIST_CONFIG.active.name = item.name;
                        }
                        else{
                            backAid = dataSource.aid;
                            backCid = cidTxt;
                            htmlArr.push('<a href="javascript:;" btn="goto_dir" aid="' + dataSource.aid + '" cid="'+cidTxt+'">' + item.name + '</a>');
                        }
                    }
                }
            }
        }

        //&raquo;
        if(dataSource.aid == 7){
            LIST_CONFIG.active.name = "回收站";
        }

        if(dataSource.aid == 30){
            LIST_CONFIG.active.name = "我的分享";
        }

        if(dataSource.aid == 31){
            LIST_CONFIG.active.name = "我的最爱";
        }

        if(dataSource.aid == 32){
            LIST_CONFIG.active.name = "最新上传";
        }

        if(dataSource.aid == 33){
            LIST_CONFIG.active.name = "待续传文件";
        }

        if(dataSource.aid == 34){
            LIST_CONFIG.active.name = "最近浏览";
        }
        if(dataSource.aid == -3){
            LIST_CONFIG.active.name = "搜索结果";
        }
        
        if(dataSource.aid == 22){
            //Page_PathStr
            if(window["Page_PathStr"]){
                for(var i = 0, len = Page_PathStr.length; i < len; i++){
                    var item = Page_PathStr[i];
                    if(i == len - 1){
                        LIST_CONFIG.active.name = item.name
                    }
                    else{
                        htmlArr.push('<a href="'+item.url+'">' + item.name + '</a>');
                    }
                }
            }
        }

        if(LIST_CONFIG.active.name == undefined){
            Util.Cookie.set("page_oldurl_cook", "");
            parent.window.location.reload();
            return;
        }
        
        htmlArr.push('<span>'+LIST_CONFIG.active.name+'</span>');

        var localBox = $("[rel='page_local']");

        var backBtn = '<a href="javascript:;" class="nav-back" btn="goto_dir" aid="'+backAid+'" cid="'+backCid+'">返回</a>';

        localBox.html(backBtn + htmlArr.join(" &raquo; "));

        localBox.append('<a href="javascript:;" class="btn-reload" onclick="window.location.reload();return false;"><i class="icon ico-reload"></i>刷新本页</a>');

        //空间数据
        var spaceBox = $("#js_space_box");
        if(dataSource.aid == 5){
            if(spaceBox.length) spaceBox.empty().remove();
        }
        else{
            if(spaceBox.length){
                spaceBox.show();
                var spaceText = spaceBox.find("[rel='space_text']");
                var spaceLine = spaceBox.find("[rel='space_line']");
                parent.window.Main.Core.SpaceData.AddClient("forever_space", function(data){
                    var key = -1;
                    if(/^1|2|3|4|9$/.test(dataSource.aid.toString())){
                        key = "1";
                    }
                    if(key && data[key]){
                        var space = data[key];
                        if(space.total){
                            spaceText.html("已用"+ Util.File.ShowSize(space.used) +"，共" + Util.File.ShowSize(space.total));
                            var persent = (space.used * 100 / space.total).toFixed(2)  + "%";
                            spaceLine.css({width: persent});
                            spaceLine.parent().attr("title", parent.window.Main.APP_NAME+ "空间使用率" + persent);
                            
                            if((space.used * 100 / space.total) > 85){
                                spaceLine.parent().addClass("red-status");
                            }
                            
                            var spaceBox = $("#js_space_box");
                            spaceBox && spaceBox.attr("used", space.used).attr("total", space.total);
                            if(parent.window.Main.Core.SpaceData.IsNoSpace()){
                                spaceBox.find("i.icon").append('<b class="ico-war"></b>');
                            }
                            
                            //同步更新上部进度信息    modify by sylar
                            var spaceBoxTop = parent.window.$("#js_space_box_top");
                            var spaceTextTop = spaceBoxTop.find("[rel='space_text']");
                            var spaceLineTop = spaceBoxTop.find("[rel='space_line']");
                            
                            if((space.used * 100 / space.total) > 85){
                            	spaceLineTop.addClass("red-status");
                            }else{
                            	spaceLineTop.removeClass("red-status");
                            }
                            
                            spaceTextTop.text(Util.File.ShowSize(space.used) +"/" + Util.File.ShowSize(space.total));
                            spaceLineTop.css({width: persent});
                        }
                    }
                })

                var is_vip = parent.window.Main.Core.FilePermission.Vip();
                
                var detailContent;
                if(is_vip){
                    detailContent = $('<div class="popup-space" style="display:none;"> <i class="arrow"></i>'+
                                            '<h3>' +parent.window.Main.APP_NAME+ '空间容量</h3>'+
                                            '<div class="space-text" style="background:#fff1de;">您好:欢迎使用' +parent.window.Main.APP_NAME+ '服务。'+
//                                                '<a href="'+parent.window.Main.Core.CONFIG.Path.VIP+'/my" target="_blank">了解详情&raquo;</a>'+
                                            '</div>'+
                                            '<ul>'+
                                                '<li><span>' +parent.window.Main.APP_NAME+ '空间：</span>'+
                                                    '<em rel="space_data"></em>'+
//                                                    '<a href="'+parent.window.Main.Core.CONFIG.Path.VIP+'/space/?p=side" target="_blank">扩容空间</a></li>'+
//                                                '<li><span>分享期限：</span>'+
//                                                    '<em rel="share_day">'+parent.window.Main.UPLOAD_CONFIG["upload_share_time"]+'</em>'+
//                                                '</li>'+
                                                '<li><span>单文件上传：</span>'+
                                                    '<em rel="up_max"></em>'+
                                                '</li>'+
                                            '</ul>'+
                                        '</div>')
                }
                else{
                    var is_vip_exp = parent.window.Main.Core.FilePermission.VipExp();
                    if(is_vip_exp){
                        
                        detailContent = $('<div class="popup-space"> <i class="arrow"></i>' +
                                                '<h3>' +parent.window.Main.APP_NAME+ '服务到期提醒 <a href="javascript:;" class="close">关闭</a></h3>' +
                                                '<div class="space-vip-expire">您购买的VIP服务已到期，请立即续费、重新开通或适当释放空间以免影响正常使用。</div>' +
                                                '<div class="space-get-vip"><a href="'+parent.window.Main.Core.CONFIG.Path.VIP_ORDER+'/?p=side" class="get-vip" target="_blank">立即续费</a> <a href="'+parent.window.Main.Core.CONFIG.Path.VIP+'/my" target="_blank">查看详情</a></div>' +
                                            '</div>');
                    }
                    else{
                        detailContent = $('<div class="popup-space" style="display:none;"> <i class="arrow"></i>'+
                                            '<h3>' +parent.window.Main.APP_NAME+ '空间容量<a href="javascript:;" class="close">关闭</a></h3>'+
                                            '<div class="space-text">您是普通会员，<b>升级为VIP</b>可获得超 大空间，超值' +parent.window.Main.APP_NAME+ '服务。'+
                                                    '<a href="'+parent.window.Main.Core.CONFIG.Path.VIP+'/helper" target="_blank">了解详情&raquo;</a>'+
                                                    '</div>'+
                                            '<ul>'+
                                                '<li><span>' +parent.window.Main.APP_NAME+ '空间：</span>'+
                                                    '<em rel="space_data"></em>'+
                                                    '<a href="'+parent.window.Main.Core.CONFIG.Path.VIP+'/space" target="_blank">扩容空间</a></li>'+
                                                '<li><span>分享期限：</span>'+
                                                    '<em rel="share_day">'+parent.window.Main.UPLOAD_CONFIG["upload_share_time"]+'</em>'+
                                                    '<a href="'+parent.window.Main.Core.CONFIG.Path.VIP_ORDER+'" target="_blank">延长期限</a></li>'+
                                                '<li><span>单文件上传：</span>'+
                                                    '<em rel="up_max"></em>'+
                                                    '<a href="'+parent.window.Main.Core.CONFIG.Path.VIP_ORDER+'/?p=side" + target="_blank">提高上限</a></li>'+
                                            '</ul>'+
                                        '</div>');
                    }
                    detailContent.find("a.close").click(function(){
                        $(this).parent().parent().hide();
                        Util.Cookie.set("right_b_tips_open", "1", 24 * 30);
                        return false;
                    });
                }
                $(document.body).append(detailContent);
                var dropDownSetting = {
                    Title: spaceBox,
                    Content: detailContent,
                    IsOverShow:true,
                    ShowHandler: function(){
                        var spaceData = spaceBox.attr("total");
//                        var upConfig = parent.window.Main.UPLOAD_CONFIG[dataSource.aid.toString()];
                        var upConfig = parent.window.Main.UPLOAD_CONFIG["1"];
                        if(upConfig){
                            detailContent.find("[rel='up_max']").html("最大" + Util.File.ShowSize(upConfig["upload_size_limit"]));
                        }

                        if(spaceData){
                            detailContent.find("[rel='space_data']").html(Util.File.ShowSize(Number(spaceData)));
                        }
                    }
                };
                Util.DropDown.Bind(dropDownSetting);
                if(!is_vip){
                    var showSpaceTips = Util.Cookie.get("right_b_tips_open");
                    if(!showSpaceTips){
                        detailContent.show();
                        dropDownSetting.ShowHandler();
                    }
                }
                
            }
        }

        
    }
    
    if(parent){
        try{
        //parent.window.Main.TopPageListenMsg();
        }catch(e){}
    }
    
//    var showSharetoTips = Util.Cookie.get("show_shareto_tips");
//    if(!showSharetoTips){
//        var btn = $('#js_page_op_menu [menu="shareto"]');
//        if(btn.length){
//            var tipsdom = $('<div class="popup-info" style="z-index:999;width:230px;display:none;"><i class="arrow"></i>' + 
//                            '<div class="popup-contents">'+
//                                '<i class="i-hint ico-war-s"></i>'+
//                                '<strong>分享升级啦！快来试一下吧</strong><br />'+
//                                '<a href="" style="color:#F63" target="_blank">整合分享给好友、微博、圈子功能。</a><br />'+
//                                '<a href="javascript:;" rel="agree_btn">我知道了，不再提示&gt;&gt;</a>'+
//                            '</div>' + 
//                        '</div>');
//            $(document.body).append(tipsdom);
//            var t = btn.offset().top + btn.height() + 8, l = btn.offset().left;
//            tipsdom.css({top:t,left:l}).show();
//            tipsdom.find("[rel='agree_btn']").bind("click",function(){
//                tipsdom.empty().remove();
//                Util.Cookie.set("show_shareto_tips", "1", 24 * 30 * 12);
//            });
//        }
//    }
    
    
    window.setTimeout(function(){
        //控制接口
        if(!NotPutAPI && parent && parent.window.Main.Core.FileConfig){
            parent.window.Main.Core.FileConfig.aid = dataSource.aid;
            parent.window.Main.Core.FileConfig.cid = dataSource.cid;
            if(!window.NotPutAPI){
                parent.window.Main.Core.FileConfig.DataAPI = DataCTL;
            }
        }
        ShowFreeMsg();
    },10);   
}

//头部按钮控制
var TopMenu = (function(){
    var _cache = {},
        _menulist = {
			"renew": {text: "续期"},
			"cancelshare": {text: "取消分享"},
            "unloading": {text: "允许转存"},
            "cancelunloading": {text: "不允许转存"},
//            "privacy": {text: "加密",ico:"lock"},
			"move": {text: "移动"},
            "edit_name": {text: "重命名", ico:"edit"},
//			"edit": {text: "备注", ico:"account"},
			"copylink": {text: "复制分享地址"},
			"delete": {text: "删除"}
        },
        _sharemenu = {
            "share": {text: "快速分享"},
            "send": {text: "好友", ico: "friend"},
            "weibo": {text: "微博"},
            "q": {text: "圈子", ico:"circle"}
        },
        _setting = {
            "dir": ["adddir", "upload", "clear", "refresh"],
            "cancelshare": ["share"],
            "doc": ["view_doc"],
            "music": ["view_music", "add_music"],
            "photo": ["view_photo"],
            "rb": ["restore", "delete_rb"],
            "sync": ["delete_sync"],
            "onefile": ["download","edit_name", "edit"],
            "send": ["send", "edit_name", "edit"],
            "more": ["more"],
            "shareto": ["shareto"],
            "morefile": ["move", "delete", "reupload", "renew"],
            "moredir": [ "delete"]
        },
        _disClass = "btn-disabled",
        _special = {
            "copy": true,
            "move": true,
            "edit": true,
            "share": true,
            //"cancelshare": true,
            "renew": true,
            "delete": true
        },
        _specialKeys = [30,31,32,33,34];
        
        if($.browser.msie){
            _setting["morefile"].push("download");
        }

    var bindEvents = function(lis){

        lis.bind("click", function(e){
            
            var btnType = $(this).attr("val");
            if(!checkButtonIsDo(btnType)){return false;}
            parent.window.Main.Core.FileMenu.DoEvent(_cache.list, btnType);
            if(_cache.floatMenu){
                _cache.floatMenu.hide();
                _cache.floatMenu.removeAttr("isover");
            }
            return false;
        })
    }

    var checkIsSpecial = function(type){
        if(_special[type]){
            for(var i = 0, len = _specialKeys.length; i < len; i++){
                if(dataSource.aid == _specialKeys[i]){
                    return true;
                }
            }
        }
        return false;
    }

    var showMenu = function(ele){
        if(!_cache.floatMenu){
            _cache.floatMenu = $('<div class="popup-menu" style="z-index:9999; display:none"></div>');
            var lisHtml = [];
            lisHtml.push('<ul>');
            for(var k in _menulist){
                var item = _menulist[k];
                var ico = item.ico? item.ico : k;
                lisHtml.push('<li><a href="javascript:;" val="'+k+'"><i class="icon ico-'+ico+'"></i>'+item.text+'</a></li>');
            }
            lisHtml.push('</ul>');
            _cache.floatMenu.append(lisHtml.join(""));
            $(document.body).append(_cache.floatMenu);
            bindEvents(_cache.floatMenu.find('[val]'));
            _cache.floatMenu.bind("mouseover", function(){
                $(this).attr("isover", "1");
            }).bind("mouseout", function(){
                $(this).removeAttr("isover");
            })
        }
        
        var lis = _cache.floatMenu.find("li");
        lis.find("i").hide();
        lis.hide();
        
        var showState = false;
        for(var i = 0, len = _cache.FloatRes.length; i < len; i++){
            var key = _cache.FloatRes[i];
            if(!checkIsSpecial(key)){
                var a = lis.find("a[val='"+key+"']");
                if(a.length){
                    a.parent().show();
                    showState = true;
                }
            }
        }

        if(showState){
            var t = ele.offset().top + 2,
                l = ele.offset().left;

            t += ele.height();
            _cache.floatMenu.css({top: t, left: l}).show();
        }
        
        window.setTimeout(function(){lis.find("i").show();} ,10);
    }

    var hideMenu = function(){
        if(_cache.floatMenu){
            if(_cache.floatMenu.attr("isover") != "1"){
                var a = _cache.floatMenu.find("[val]");
                a.parent().hide();
                _cache.floatMenu.hide();
                _cache.floatMenu.removeAttr("isover");
            }
        }
    }

    var setStatus = function(btnRes, floatRes, shareRes){
        _cache.BtnRes = btnRes;
        _cache.FloatRes = floatRes;
        _cache.ShareRes = shareRes;
        var menuBox = $("#js_page_op_menu");
        var menus = menuBox.find("[menu]");
        menus.addClass(_disClass);

        hideMenu();
        if(floatRes.length){
            btnRes.push("more");
            if(_cache.list.length > 1 && (dataSource.aid != 4 && dataSource.aid != 3)){
                var moreBtn = $("#js_page_op_menu").find("[menu='more']");
                moreBtn.length && showMenu(moreBtn);
            }
        }
        
        if(shareRes.length){
            btnRes.push("shareto");
        }
        
        
        for(var i = 0, len = btnRes.length; i < len; i++){
            var list = _setting[btnRes[i]];
            if(list){
                for(var j = 0, jlen = list.length; j < jlen; j++){
                    var type = list[j];
                    menuBox.find("[menu='" + type + "']").removeClass(_disClass);
                }
            }
        }
        
    }

    var checkButtonIsDo = function(type){
        var res = parent.window.Main.Core.FileMenu.CheckButtonIsDo(_cache.list, type);
        if(res){
            if(typeof res == "object"){
                _cache.list = res;
            }
            return true;
        }
        else{
            return false;
        }
    }

    return {
       HideMenu: function(){
           hideMenu();
       },
       CheckButtonIsDo: function(type){
           return checkButtonIsDo(type);
       },
       CheckMenu: function(arr, x, y){
           if(NotPutAPI) return;
           var fileCount = 0,  //文件数量
               folderCount = 0,
               shareCount = 0,
               btnRes = [],
               floatRes = [],
               shareRes = [];  //目录数量

           _cache.list = arr;   //缓存列表

           if(arr && arr.length){
               if(dataSource.aid == 7){
                   btnRes.push("rb");
               }
               if(dataSource.aid == 22){
                   btnRes.push("sync");
               }
               else{
                   
                   for(var i = 0, len = arr.length; i < len; i++){
                       var item = arr[i];
                       var file_type = item.attr("file_type");
                       if(file_type == "1"){
                            fileCount++;
                        }
                        else if(file_type == "0"){
                            folderCount++;
                        }
                       if(item.attr("is_share") == "1"){
                           shareCount++;
                       }
                   }

                   if(shareCount != (fileCount + folderCount)){
                       if(folderCount && parent.window.Main.Core.FilePermission.SharedDir(dataSource.aid)){
                           btnRes.push("cancelshare");
                       }
                       if(fileCount && !folderCount){
                           btnRes.push("cancelshare");
                       }
                   }

                   if(folderCount == 0 && fileCount == 1){
                       btnRes.push("onefile");
                       switch(dataSource.aid){
                           case 2:
                               btnRes.push("doc");
                               break;
                       }
                   }
                   
                   if(folderCount == 1 && fileCount == 0){
                       btnRes.push("send");
                   }
                   
                   if(folderCount){
                       btnRes.push("moredir");
                   }
                   
                   if(fileCount > 0 && folderCount == 0){
                       btnRes.push("morefile");
                       btnRes.push("send");
                       switch(dataSource.aid){
                           case 2:
                               btnRes.push("doc");
                               break;
                           case 3:
                               btnRes.push("photo");
                               break;
                           case 4:
                               btnRes.push("music");
                               break;
                       }
                       
                   }
               }
               floatRes = parent.window.Main.Core.FileMenu.CheckType(dataSource.aid, dataSource.cid,arr);
               var hasShare = false;
               for(var i = 0, len = floatRes.length; i < len; i++){
                   if(_sharemenu[floatRes[i]]){
                       hasShare = true;
                       break;
                   }
               }
               if(hasShare){
                   shareRes = parent.window.Main.Core.FileMenu.CheckType(dataSource.aid, dataSource.cid,arr);
               }
           }
           btnRes.push("dir");
           setStatus(btnRes, floatRes, shareRes);
       },
	   doClick: function(ele){
             if(!checkButtonIsDo(ele.attr("menu"))){return false;}
	   		 switch(ele.attr("menu")){
			   case "star":
				   var star = ele.attr("is_star") == "1"? 0 : 1;
				   var file_id = ele.parents("[file_id]").attr("file_id");
				   if(file_id){
					   parent.window.Main.Core.FileAjax.Star(file_id, star, function(){
						   if(star){
							   ele.attr("is_star", "1");
							   ele.addClass("star-collect");
						   }
						   else{
							   ele.removeAttr("is_star");
							   ele.removeClass("star-collect");
						   }
					   })
				   }
				   break;
			   case "location":
	                var exif       = ele.attr("is_exif");
	                var tpl        = ele.attr("tpl");
	                var name       = ele.attr("file_name");
	                var file_id    = ele.parents("[file_id]").attr("file_id");
	                var cid        = ele.parents("[file_id]").attr("p_id");
	                var version_id = ele.parents("[file_id]").attr("file_version_id");
	                var gps        = ele.parents("[file_id]").attr("file_gps");
	                if (file_id) {
	                    if (exif) {
	                        //
	                        // 如果存在,直接加载地图
	                        //
	                        parent.window.PageCTL .GOTO_URL(parent.PAGE_PATHS["MY"]+"/index.php?r=List/index&aid=35&flag=1&exif=" + exif + "&tid=" + file_id + "&cid=" + cid + "&version=" + version_id + "&name=" + name + "&tpl=" + tpl + "&gps=" + gps);
	                    } else {
	                        // TODO:
//	                        parent.window.Main.Core.FileExifDG.Show(file_id,
//	                                "x");
	                    }
	                }
	                break;
			   case "cancelshare":
				   var action = parent.window.Main.Core.FileMenu.Action("share");
				   action && action(_cache.list, "cancelshare");
				   break;
			   case "share":
				   var action = parent.window.Main.Core.FileMenu.Action("share");
				   action && action(_cache.list, "share");
				   //parent.window.Main.Core.SendFileDG.Open(_cache.list, "file");
				   break;
			   case "renew":
				   var action = parent.window.Main.Core.FileMenu.Action("share");
				   action && action(_cache.list, "renew");
				   break;
			   case "adddir":
				   parent.window.Main.Core.Dir.Create(dataSource.aid, dataSource.cid);
				   break;
			   case "move":
				   parent.window.Main.Core.TreeDG.Show({
						list: _cache.list,
						type: "move"
					});
					break;
			   case "upload":
				   parent.window.Main.Core.Upload.Show(dataSource.aid, dataSource.cid);
				   //parent.window.Main.Core.Upload.Open();
				   break;
			   case "clear":
				   parent.window.Main.Core.FileAjax.ClearRB();
				   break;
			   case "restore":
				   var tids = [];
					for(var i = 0, len = _cache.list.length; i < len; i++){
						var item = _cache.list[i];
						tids.push(item.attr("tid"));
					}
				   parent.window.Main.Core.FileAjax.RestoreRB(tids);
				   break;
			   case "delete_rb":
				   var tids = [];
					for(var i = 0, len = _cache.list.length; i < len; i++){
						var item = _cache.list[i];
						tids.push(item.attr("tid"));
					}
				   parent.window.Main.Core.FileAjax.DeleteRB(tids);

				   break;
			   case "refresh":
				   window.location.reload();
				   break;
			   case "delete_sync":
				   parent.window.Main.Core.Message.Confirm({
						text: '确认要删除选中的文件或文件夹吗？',
						type: "war",
						callback: function(r){
							if(r){
								window["DoEventObject"] && DoEventObject.DeleteSync(_cache.list);
							}
						}
				   })
				   break;
			   case "more":
				   showMenu(ele);
				   break;
			   case "shareto":
				   //showShareMenu(ele);
				   var sharelist = {"weibo":1, "q":1, "share":1, "send":1};
				   var openCondition = {};
				   if(_cache.ShareRes){
					   for(var i = 0, len = _cache.ShareRes.length; i < len; i++){
						   if(sharelist[_cache.ShareRes[i]]){
							   openCondition[_cache.ShareRes[i]] = 1;
						   }
					   }
				   }
				   parent.window.Main.Core.FileAPI.ShareTO(_cache.list, openCondition);
				   break;
			   case "view_photo":
			       var start   = _cache.list[0].attr('s');
			       var limit   = _cache.list[0].attr('limit');
				   var file_id = _cache.list[0].attr("file_id");
				   var ids     = _cache.list[0].attr("ids");
				   parent.window.Main.Core.PhotoView.Show(dataSource.aid, dataSource.cid, file_id, _cache.list[0].attr("is_online"), start, limit, ids);
				   break;
			   case "view_doc":
				   var pick_code = _cache.list[0].attr("pick_code");
				   parent.window.Main.Core.Reader.Open(pick_code);
				   break;
			   case "view_music":
				   var addList = [];
				   for(var i = 0, len = _cache.list.length; i < len; i++){
					   var itemNode = _cache.list[i];
					   addList.push({name: itemNode.find('[field="file_name"]').attr("title"), mp3: itemNode.attr("path")});
				   }
				   parent.window.Main.Core.MusicPlayer.Add(addList, true);
				   break;
			   case "add_music":
				   var addList = [];
				   for(var i = 0, len = _cache.list.length; i < len; i++){
					   var itemNode = _cache.list[i];
					   addList.push({name: itemNode.find('[field="file_name"]').attr("title"), mp3: itemNode.attr("path")});
				   }
				   parent.window.Main.Core.MusicPlayer.Add(addList);
				   break;
			   case "download":
                   parent.window.Main.Core.FileMenu.DoEvent(_cache.list, "download");
				   break;
			   case "send":
				   var action = parent.window.Main.Core.FileMenu.Action("send");
				   action && action(_cache.list, "send");
				   break;
			   case "delete":
				   parent.window.Main.Core.FileMenu.DoEvent(_cache.list, "delete");
				   break;
			   case "privacy":
				   parent.window.Main.Core.FileMenu.DoEvent(_cache.list, "privacy");
				   break;
			   case "close_share":
				   parent.window.Main.Core.FileAjax.AllowCollect(_cache.list, 0);
				   break;
			   case "open_share":
				   parent.window.Main.Core.FileAjax.AllowCollect(_cache.list, 1);
				   break;
			   case "reupload":
				   if(_cache.list && _cache.list.length){
					   var pickcodes = [];
					   for(var i = 0, len = _cache.list.length; i < len; i++){
						   pickcodes.push(_cache.list[i].attr("pick_code"));
					   }
					   
					   parent.window.Main.Core.Upload.ReuploadByPickCode(pickcodes);
				   }
				   break;
               case "edit_name":
                   parent.window.Main.Core.FileMenu.DoEvent(_cache.list, "edit_name");
                   break;
			   default:
				   parent.window.Main.Core.MinMessage.Show({text: ele.attr("menu") + " " + _cache.list.length ,type:"suc", timeout: 2000});
				   break;
		   }
	   },
       Init: function(){
           //var menuBox = $("#js_page_op_menu");
           //var menuBox = $(document.body);
           $(document).bind("click", function(e){
               var ele = $(e.target);
               if(ele.hasClass(_disClass)) return false;
               hideMenu();
               if(ele.attr("menu")){
                   TopMenu.doClick(ele);
                   return false;
               }
           })
           $('[menu="more"]').bind("mouseover", function(e){
               var ele = $(this);
               _cache.more_show_timer = window.setTimeout(function(){
                   if(ele.hasClass(_disClass)) return false;
                   showMenu(ele);
               },200);
           }).bind("mouseout", function(e){
               if(_cache.more_show_timer){
                   window.clearTimeout(_cache.more_show_timer);
               }
           })
       }
    }
})();

var PageCommmon = {
    ResetFileName: function(){
        var inner = $("#js_data_list_inner");
        if(inner.length){
            var w = inner.width();
            inner.find("dt li").not(".file-name").each(function(){
                w -= $(this).width();
            });
            var fileNamelen = w;
            inner.find("dt li.file-name").width(fileNamelen - 27);
            inner.find("dd li.file-name").width(fileNamelen - 50);
        }
    }
}

//页面加载后初始化方法
function PageLoadInit() {
    try {
        window.frameElement;
        // Success! Show the time taken.
        
        if(!NotPutAPI){
            TopMenu.Init();
            
            $(document).ready(function(){
                PageInitFun();
                
                var pagesBox = $("div.pages");
                var isadd = true;
                if(pagesBox.length){
                    var w = pagesBox.width();
                    var prev = pagesBox.find(".btn-prev");
                    if(prev.length && prev.offset().left < 225 + 5){
                        isadd = false;
                    }
                }
                
                if(isadd){
                    var adiframe = $('<iframe id="frame_tjj_32" style="height:18px;width:225px;position: absolute;left:5px;bottom:5px;" src="/statics/web/delivery/d_32.html" scrolling="no" frameborder="0"></iframe>');
//                    $(document.body).append(adiframe);
                    $(window).bind("resize", function(){
                        var pagesBox = $("div.pages");
                        var isadd = true;
                        if(pagesBox.length){
                            var w = pagesBox.width();
                            var prev = pagesBox.find(".btn-prev");
                            if(prev.length && prev.offset().left < 225 + 5){
                                isadd = false;
                            }
                        }
                        if(isadd){
                            adiframe.show();
                        }
                        else{
                            adiframe.hide();
                        }
                    })
                }
            })
        }
        PageBindEventFun();
        
    } catch (e) {
        // Failure. Try again in 100ms.
        setTimeout(PageLoadInit, 100);
    }
}

PageLoadInit();
